/*
 * Copyright 2009-2010 Nanjing RedOrange ltd (http://www.red-orange.cn)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package redora.client.util;

import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.client.ui.HasWidgets;
import redora.client.Persistable;

import java.util.ArrayList;

/**
 * Utility to move information from client side pojo's back and
 * forth to widgets and json. Note the convention: the copy functions
 * perform a passive copy from the left argument to the right. The
 * from functions search for any cached versions of the target object
 * or instantiate them for you.
 * @author Nanjing RedOrange (www.red-orange.cn)
 * @param <T>
 */
public interface ClientUtil<T extends Persistable> {
    /** yyyy-MM-dd */
    public static final DateTimeFormat DATE =
            DateTimeFormat.getFormat("yyyy-MM-dd");
    /** yyyy-MM-dd HH:mm:ss */
    public static final DateTimeFormat DATETIME =
            DateTimeFormat.getFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * Copies given Persistable pojo to the form panel. Make sure the given fields are available
     * on the panel. If the pojo is omitted, a new Product will be created so the form
     * will be set to the correct default values.
     * @param pojo (Optional) The data
     * @param panel (Mandatory) The form panel
     * @param fields (Mandatory) The fields that are decorated on the panel.
     */
    void copy(T pojo, HasWidgets panel, ArrayList<Field> fields);

    /**
     * Copies the data on the panel to the given pojo. Only given fields are copied.
     *
     * @param panel
     * @param pojo
     * @param fields
     */
    void copy(HasWidgets panel, T pojo, ArrayList<Field> fields);

    /**
     * @param obj
     * @return A pojo from given JSON source. According to the Scope fields will be populated.
     */
    T from(JSONObject obj);

    /**
     * Constructs an array of values of given fields from the pojo
     * @param pojo (Mandatory)
     * @param fields (Mandatory)
     * @return fields.length array with field values as string
     */
    String[] from(T pojo, Field[] fields);
}
